//
//  NHTSorBtnView.swift
//  TestIos
//
//  Created by 李亚东 on 2025/11/5.
//  Copyright © 2025 Liyadong. All rights reserved.
//

import UIKit
import SnapKit

@available(iOS 13.0, *)
class NHTSorBtnView: UIView {
    
    // MARK: - UI Components
    
    /// 标题标签
    private let titleLabel: UILabel = {
        let label = UILabel()
        label.textColor = .label
        label.font = .systemFont(ofSize: 16)
        label.textAlignment = .left
        label.baselineAdjustment = .alignCenters
        return label
    }()
    
    /// 三角形图标视图
    private let triangleImageView: UIImageView = {
        let imageView = UIImageView()
        imageView.contentMode = .center
        imageView.tintColor = .label
        return imageView
    }()
    
    // MARK: - State Properties
    
    /// 当前旋转角度
    private var currentRotationAngle: CGFloat = 0
    
    /// 标记是否在初始化中（用于避免初始化时触发动画）
    private var isInitializing: Bool = true
    
    // MARK: - Public Properties
    
    /// 标题文本
    var title: String = "" {
        didSet {
            titleLabel.text = title
        }
    }
    
    /// 展开状态
    /// - true: 展开状态（三角图标向上，旋转180度）
    /// - false: 收起状态（三角图标向下，初始状态）
    var isExpanded: Bool = false {
        didSet {
            guard isExpanded != oldValue else { return }
            guard !isInitializing else { return }
            animateRotation(to: isExpanded, animated: true)
        }
    }
    
    /// 点击回调
    var onTap: (() -> Void)?
    
    // MARK: - Initialization
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
        setupGesture()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupUI()
        setupGesture()
    }
    
    // MARK: - UI Setup
    
    /// 设置UI布局
    private func setupUI() {
        backgroundColor = .systemBackground
        
        // 创建并配置三角形图标
        createTriangleIcon()
        
        // 创建容器视图用于整体居中布局
        let containerView = createContainerView()
        
        // 设置约束
        setupConstraints(containerView: containerView)
        
        // 初始化完成，允许执行动画
        isInitializing = false
    }
    
    /// 创建容器视图
    private func createContainerView() -> UIView {
        let containerView = UIView()
        addSubview(containerView)
        containerView.addSubview(titleLabel)
        containerView.addSubview(triangleImageView)
        return containerView
    }
    
    /// 设置约束
    private func setupConstraints(containerView: UIView) {
        // 容器视图约束：水平居中
        containerView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.centerY.equalToSuperview()
            make.height.equalToSuperview()
        }
        
        // 三角形图标约束
        triangleImageView.snp.makeConstraints { make in
            make.trailing.equalToSuperview()
            make.centerY.equalToSuperview()
            make.width.height.equalTo(12)
        }
        
        // 标题标签约束：与图标垂直居中对齐
        titleLabel.snp.makeConstraints { make in
            make.leading.equalToSuperview()
            make.trailing.equalTo(triangleImageView.snp.leading).offset(-4)
            make.centerY.equalTo(triangleImageView.snp.centerY)
        }
    }
    
    /// 创建三角形图标
    private func createTriangleIcon() {
        // 绘制向下三角形（顶点在上，底边在下）
        let trianglePath = UIBezierPath()
        trianglePath.move(to: CGPoint(x: 0, y: 3))
        trianglePath.addLine(to: CGPoint(x: 12, y: 3))
        trianglePath.addLine(to: CGPoint(x: 6, y: 9))
        trianglePath.close()
        
        // 创建形状图层
        let triangleLayer = CAShapeLayer()
        triangleLayer.path = trianglePath.cgPath
        triangleLayer.fillColor = UIColor.label.cgColor
        triangleLayer.frame = CGRect(x: 0, y: 0, width: 12, height: 12)
        
        // 转换为图片
        let renderer = UIGraphicsImageRenderer(size: CGSize(width: 12, height: 12))
        let image = renderer.image { context in
            triangleLayer.render(in: context.cgContext)
        }
        
        triangleImageView.image = image.withRenderingMode(.alwaysTemplate)
    }
    
    // MARK: - Gesture Handling
    
    /// 设置手势识别
    private func setupGesture() {
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap))
        addGestureRecognizer(tapGesture)
        isUserInteractionEnabled = true
    }
    
    /// 处理点击手势
    @objc private func handleTap() {
        isExpanded.toggle()
        onTap?()
    }
    
    // MARK: - Animation
    
    /// 执行旋转动画
    /// - Parameters:
    ///   - expanded: 目标展开状态
    ///   - animated: 是否执行动画，默认为 true
    private func animateRotation(to expanded: Bool, animated: Bool = true) {
        let targetAngle: CGFloat = expanded ? .pi : 0
        let rotationDelta = calculateRotationDelta(expanded: expanded, targetAngle: targetAngle)
        
        if animated {
            performAnimatedRotation(rotationDelta: rotationDelta, targetAngle: targetAngle)
        } else {
            applyRotationImmediately(targetAngle: targetAngle)
        }
    }
    
    /// 计算旋转增量
    private func calculateRotationDelta(expanded: Bool, targetAngle: CGFloat) -> CGFloat {
        if expanded {
            // 展开：顺时针旋转180度（正值）
            return .pi - currentRotationAngle
        } else {
            // 收起：逆时针旋转180度（负值）
            return -currentRotationAngle
        }
    }
    
    /// 执行动画旋转
    private func performAnimatedRotation(rotationDelta: CGFloat, targetAngle: CGFloat) {
        UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseInOut) {
            self.triangleImageView.transform = self.triangleImageView.transform.rotated(by: rotationDelta)
        } completion: { _ in
            self.currentRotationAngle = targetAngle
            // 确保最终状态正确（避免累积误差）
            self.triangleImageView.transform = CGAffineTransform(rotationAngle: targetAngle)
        }
    }
    
    /// 立即应用旋转（无动画）
    private func applyRotationImmediately(targetAngle: CGFloat) {
        currentRotationAngle = targetAngle
        triangleImageView.transform = CGAffineTransform(rotationAngle: targetAngle)
    }
    
    // MARK: - Public Methods
    
    /// 重置到初始状态（向下，无动画）
    func reset() {
        isInitializing = true
        isExpanded = false
        currentRotationAngle = 0
        triangleImageView.transform = .identity
        isInitializing = false
    }
}
